//
//  AppDelegate.m
//  Molian
//
//  Created by wansong on 3/16/15.
//  Copyright (c) 2015 xiaocan. All rights reserved.
//
/**********************
 ┏┓　　 　┏┓
 ┏┛┻━━━━━┛┻┓
 ┃         ┃
 ┃    ━    ┃
 ┃　┳┛　┗┳　 ┃
 ┃         ┃
 ┃    ┻    ┃
 ┃         ┃
 ┗━┓　　　┏━┛
 ┃　　　┃ 神兽保佑
 ┃　　　┃ 代码无BUG！
 ┃　　　┗━━━┓
 ┃         ┣┓
 ┃         ┏┛
 ┗┓┓┏━━━┳┓┏┛
 ┃┫┫   ┃┫┫
 ┗┻┛   ┗┻┛
 **********************/
#import "AppDelegate.h"
#import "MLTabBar.h"
#import <AVOSCloudSNS.h>
#import "RongCloudService.h"
//友盟
#import "UMSocialWechatHandler.h"
#import "UMSocialQQHandler.h"
#import "UMSocialSinaHandler.h"
#import "MLHomeViewController.h"
#import <CommonCrypto/CommonDigest.h>
#import <UIImage+GIF.h>
#import "LoginViewController.h"
#import "NotificationService.h"
#import "CallViewController.h"
#import "AppDelegate+EaseMob.h"
#import <AVOSCloudCrashReporting/AVOSCloudCrashReporting.h>
#import "GifView.h"
#define kNumber 300

@interface AppDelegate ()
@property NSString *wxCode;
@property NSString *wxAccessToken;
@property NSString *wxOpenid;


// 语音通话
@end

@implementation AppDelegate
{
    NSInteger biaoji;
}
//
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//    // 根据推送的数据进行相应处理
//    //新增处理后台获取数据操作
//    //
//
//   // NSLog(@"didReceiveRemoteNotification%@",userInfo);
//
//    completionHandler(UIBackgroundFetchResultNewData);
//}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    //注册失败
    NSLog(@"%@",error);
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    
    if (application.applicationState == UIApplicationStateActive) {
        [NotificationService handleRemoteNotification:userInfo];
        // 此处可以写上应用激活状态下接收到通知的处理代码，如无需处理可忽略
        //前台运行时执行
    } else {
        // The application was just brought from the background to the foreground,
        // so we consider the app as having been "opened by a push notification."
        [AVAnalytics trackAppOpenedWithRemoteNotificationPayload:userInfo];
    }
    
    
    
    
    
}


//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
//{
//    NSLog(@"2");
//}
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSLog(@"didReceiveLocalNotification");
    
}
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    
#if!TARGET_IPHONE_SIMULATOR
    //register to receive notifications
    [application registerForRemoteNotifications];
#endif
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
   
   
   
    
    
    
    
    _connectionState = eEMConnectionConnected;
    
    //推送配置
    if (IS_IOS8) {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert| UIUserNotificationTypeBadge| UIUserNotificationTypeSound categories:nil];
        [application registerUserNotificationSettings:settings];
        [application registerForRemoteNotifications];
    }else{
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeAlert |UIRemoteNotificationTypeSound];
    }
    if (application.applicationState != UIApplicationStateBackground) {
        // Track an app open here if we launch with a push, unless
        // "content_available" was used to trigger a background push (introduced
        // in iOS 7). In that case, we skip tracking here to avoid double
        // counting the app-open.
        BOOL preBackgroundPush = ![application respondsToSelector:@selector(backgroundRefreshStatus)];
        BOOL oldPushHandlerOnly = ![self respondsToSelector:@selector(application:didReceiveRemoteNotification:fetchCompletionHandler:)];
        BOOL noPushPayload = ![launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (preBackgroundPush || oldPushHandlerOnly || noPushPayload) {
            [AVAnalytics trackAppOpenedWithLaunchOptions:launchOptions];
        }
    }
    
    biaoji = 0;
    
    /********注册AVOS服务*********/
    [MLUser registerSubclass];
    [MLGallery registerSubclass];
    [MLFeedback registerSubclass];
    [MLWithdraw registerSubclass];
    [MLAuthentication registerSubclass];
    [MLReportRecord registerSubclass];
    [MLChatBackground registerSubclass];
    [MLSleep registerSubclass];
    [MLArticle registerSubclass];
    [MLTopic registerSubclass];
    [MLRecommendUser registerSubclass];
    [MLUserLike registerSubclass];
    [MLArticleLike registerSubclass];
    [MLArticleComment registerSubclass];
    [MLArticleShare registerSubclass];
    [MLDate registerSubclass];
    [MLPaidVoip registerSubclass];
    [MLFriendApply registerSubclass];
    [MLVoice registerSubclass];
    [MLTask registerSubclass];
    [MLConsumeRecord registerSubclass];
    [MLCallRecord registerSubclass];
    [MLCustomizationRecord registerSubclass];
    [MLLovers registerSubclass];
    [MLWebpageRecharge registerSubclass];
    [MLInfoChangeNotify registerSubclass];
    [MLException registerSubclass];
    [MLSignRecord registerSubclass];
    [MLGift registerSubclass];
    [MLGiftRecord registerSubclass];
    [MLSweetheart registerSubclass];
    [MLSweetheartApply registerSubclass];
    [MLIncomeRecord registerSubclass];
    [MLCircle registerSubclass];
   //开启崩溃
    [AVOSCloudCrashReporting enable];
   
    [AVOSCloud setApplicationId: AVOS_APP_ID clientKey: AVOS_APP_KEY];

    
    
    
    
    
    
    //友盟
    [UMSocialData setAppKey:UM_KEY];
    [UMSocialConfig hiddenNotInstallPlatforms:@[UMShareToQQ,UMShareToQzone,UMShareToWechatSession,UMShareToWechatTimeline]];
    //设置微信AppId,设置分享url,默认使用友盟的网址
    [UMSocialWechatHandler setWXAppId:@"wxea476b03fadc1c2a" appSecret:@"77d1eabc50fac1436a2949dd7fd6af8c" url:@"http://www.pocketsweet.com/wap"];
    //    //设置分享到QQ空间的应用Id,和分享url 链接
    [UMSocialQQHandler setQQWithAppId:@"1104588970" appKey:@"JVSuqFVQjNWJJvSI" url:@"http://www.pocketsweet.com/wap"];
    //    //设置支持没有客户端情况下使用SSO授权
    
    [UMSocialQQHandler setSupportWebView:YES];
    [UMSocialSinaHandler openSSOWithRedirectURL:WEIBO_REDIRECT_URI];
    //微信
    [WXApi registerApp:@"wxaa055b4833fdbf4a"];
    
    [MobClick startWithAppkey:UM_KEY reportPolicy:BATCH channelId:nil];
    
    // 环信
    //    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    //    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    //    [[EMSDKFull sharedInstance].callManager addDelegate:self delegateQueue:nil];
    // 初始化环信SDK，详细内容在AppDelegate+EaseMob.m 文件中
    [self easemobApplication:application didFinishLaunchingWithOptions:launchOptions];
    
    //设置导航栏颜色
    [[UINavigationBar appearance] setBarStyle:UIBarStyleBlackOpaque];//导航栏颜色
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];//状态栏颜色
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];//导航栏back等颜色
    [[UINavigationBar appearance]setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor],NSFontAttributeName:[UIFont systemFontOfSize:18]}];////导航栏Title颜色
    [[UINavigationBar appearance] setBackgroundImage:[UIImage imageWithColor:RGBA(31, 30, 30, 0.99)] forBarMetrics:UIBarMetricsDefault];
    //    [[UINavigationBar appearance]setTranslucent:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onAutologinToEasemob) name:@"loginEaseMob" object:nil];
    
    
    MLUser *user = [MLUser currentUser];
    
    if (!user.nickname) {
        [MLUser logOut];
    }
    if (user) {
        //刷新用户金钱判断用户的资金变化
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            AVQuery *q = [MLUser query];
            [q whereKey:@"objectId" equalTo:user.objectId];
            [q getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {
                if (error) {
                    
                }else{
                    MLUser *nUser = (MLUser *)object;
                    NSUserDefaults *uD = [NSUserDefaults standardUserDefaults];
                    NSString *str = [NSString stringWithFormat:@"%@balance",nUser.objectId];
                    NSString *blance = [uD objectForKey:str];
                     [uD setObject:[NSString stringWithFormat:@"%f",nUser.balance] forKey:str];
                    [uD synchronize];
                    if (blance&&blance.length>0) {
                        CGFloat pristineBlance = [blance floatValue];
                        CGFloat nBlance = nUser.balance - pristineBlance;
                       
                        if (nBlance>=30) {
                            MLException *exception = [MLException object];
                            exception.user = nUser;
                            exception.sum = nBlance;
                            [exception saveInBackground];
                        }
                    }else{
                        
                    }
                }
            }];
        });
    }
    
    
    #pragma mark 
    self.window.backgroundColor = [UIColor whiteColor];
    self.window.rootViewController = [[MLTabBar alloc]init];
    // 判断用户是否已登录
    if (user.isUserInited) {
        user.lastLogin = [NSDate date];
        if (![AVInstallation currentInstallation].installationId) {
            [self installation];
        }
        
//        BOOL isAutoLogin = [[EaseMob sharedInstance].chatManager isAutoLoginEnabled];
//        //判断环信是否登录
//        if (!isAutoLogin || ![[EaseMob sharedInstance].chatManager isConnected]) {
//            [self onAutologinToEasemob];
//        }
//        if (![[EaseMob sharedInstance].chatManager isConnected]) {
//            [self autologinToEasemob];
//        }
       // [user saveInBackground];
        
        if (!user.subAvatar||user.subAvatar.length == 0) {
            AVFile *file = [AVFile fileWithURL:user.avatar.url];
            NSString *nstr = [file getThumbnailURLWithScaleToFit:YES width:100 height:100 quality:100 format:@"png"];
            user.subAvatar = nstr;
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                // 重新加载图片
                //更换头像,通知好友列表
              
            }];
        }
       
    }else{
        [MLUser logOut];
    }
    
  //  [AVOSCloud setAllLogsEnabled:YES];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [user refreshInBackgroundWithBlock:^(AVObject *object, NSError *error) {
            MLUser *cuser = (MLUser *)object;
            if (cuser.status == MLUserStatus_DISABLE) {
                [self appout];
            }
        }];
    });
   // [MobClick checkUpdateWithDelegate:self selector:@selector(UP:)];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //查询配置文件
        AVQuery *query = [MLWebpageRecharge query];
        NSDictionary *infoDict = [[NSBundle mainBundle] infoDictionary];
       NSString *version = [NSString stringWithFormat:@"%@",[infoDict objectForKey:@"CFBundleShortVersionString"]];
        [query whereKey:@"CFBundleShortVersionString" equalTo:version];
        [query getFirstObjectInBackgroundWithBlock:^(AVObject *object, NSError *error) {

            if (error) {
                //检查原因
            }else{
                MLWebpageRecharge *configuration = (MLWebpageRecharge *)object;
                NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:@(configuration.chatCharge),@"chatCharge", @(configuration.normal),@"normal",configuration.content,@"content",@(configuration.screen),@"screen" , configuration.CFBundleShortVersionString,@"CFBundleShortVersionString",configuration.webpage,@"webpage",@(configuration.withdraw),@"withdraw",@(configuration.emotionalHotline),@"emotionalHotline",@(configuration.changeImage),@"changeImage",@(configuration.signClock),@"signClock",@(configuration.topic),@"topic", nil];
                [Utils AddToPlistWithPlistName:@"configuration" andDictionary:dic];
            }
            
        }];
        
        
    });
    
    //app没有启动,点击通知时
    if(launchOptions){
        [NotificationService handleRemoteNotification:launchOptions];
    }
    
    return YES;
}


-(void)appout
{
    
    //  [HUD Prompt:@"账号被禁用了,请联系客服"];
    [Utils alert:@"账号被禁用了,请联系客服"];
    //退出登录
    [Utils quitLogin];
    
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
        if(error){
            [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
            } onQueue:nil];
        }
    } onQueue:nil];
    
    UITabBarController *tabbar = (UITabBarController*)self.window.rootViewController;
    tabbar.selectedIndex = 1;
}

//升级检测
-(void)UP:(NSDictionary *)sender
{
    NSString *update = [sender objectForKey:@"update"];
    if ([update isEqualToString:@"YES"]) {
        NSString *Title = [NSString stringWithFormat:@"发现新版 %@!",[sender objectForKey:@"version"]];
        NSString *Content = [NSString stringWithFormat:@"%@",[sender objectForKey:@"update_log"]];
        
        if ([Content isEqualToString:@"强制更新"]) {
            HUD *hud = [[HUD alloc]init];
            [hud HUDImage:[UIImage imageNamed:@"img_noti_02"] Title:@"" Content:Title CANCEL:@"不更新" Confirm:@"现在升级"];
            hud.Confirm  = ^{
                NSString *path = [sender objectForKey:@"path"];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:path]];
                exit(0);
            };
            hud.Cancel  = ^{
                exit(0);
            };
            [self.window.rootViewController.view addSubview:hud];
            return;
        }
    }
}

-(void)installation
{
    if (biaoji <5) {
        
        MLUser *user = [MLUser currentUser];
        if (user.isUserInited) {
            AVInstallation *installation = [AVInstallation currentInstallation];
            NSArray *objects;
            if (user.type == MLUserType_NORMAL) {
                objects = @[user.objectId];
            }else if (user.gender==MLUserGender_MALE) {
                objects = @[user.objectId,@"SweetMale"];
            }else{
                objects = @[user.objectId,@"SweetFemale"];
            }
            [installation addUniqueObjectsFromArray:objects forKey:@"channels"];
            [installation saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (error) {
                    NSLog(@"远程通知错误");
                    // [self installation];
                    biaoji ++;
                }
                NSLog(@"error = %@",error);
                NSLog(@"通知注册结果%@",succeeded ? @"通知注册成功":@"通知注册错误");
            }];
        }
    }
}
//计算剩余时间
- (NSInteger)manageDateBeginDate:(NSDate *)beginDate presentDate:(NSTimeInterval)presentInterval buyMinute:(NSInteger )buyMinute
{
    NSTimeInterval begin = [beginDate timeIntervalSince1970];
    NSTimeInterval cha = (presentInterval - begin);
    NSTimeInterval buy = buyMinute * 60;
    return buy - cha;
}

//打开应用登录判断是否需要请求好友,喜欢
- (void)onAutologinToEasemob
{
    [self autologinToEasemob];
    MLUser *user = [MLUser currentUser];
    if (user&&[MLUser currentUser].isUserInited&&MLUserStatus_DISABLE != user.status) {
        //加载好友关系
        
        NSDictionary *dic = [Utils getPassFriend];
        if (dic == nil) {
            [self loadFriendsData];
        }
        //加载喜欢的人
        NSDictionary *dicLoveUser = [Utils getPassFriend];
        if (dicLoveUser == nil) {
            [self loadLikeUserData];
        }
       //加载喜欢的文章
        NSDictionary *dicLoveArticle = [Utils getPassFriend];
        if (dicLoveArticle == nil) {
            [self loadLikeArticleData];
        }
    }
}
//自动登录调用的方法
- (void)autologinToEasemob{
    MLUser *user = [MLUser currentUser];
    if (user == nil) {
        return;
    }
    if (MLUserStatus_DISABLE == user.status) {
        [self appout];
        return;
    }
    if (user) {
        
        [[EaseMob sharedInstance].chatManager setApnsNickname:user.nickname];
//        if ([Utils cheackConfigurationUserHint]) {
//            //致新用户
//            [[ShareData shareData].homeVC.find xsimge];
//        }else{
//            
//            
//        }
        [[ShareData shareData].firstView login];
        [[ShareData shareData].secondView login];
        [[ShareData shareData].thirdView  login];
      
        [HUD setOnViewWithTitle:@"登录中" animated:YES];
        [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:user.objectId password:[self md5:user.objectId] completion:^(NSDictionary *loginInfo, EMError *error) {
            [HUD hideFromViewAnimated:YES];
            if (!error && loginInfo) {
                [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                //获取群组列表
                [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
                NSLog(@"登录成功");
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"logOutSucceed" object:nil];
                [[EaseMob sharedInstance].chatManager setApnsNickname:user.nickname];
                // 设置自动登录
                [self inituserdata];
                
                [[EaseMob sharedInstance].chatManager.pushNotificationOptions setDisplayStyle:ePushNotificationDisplayStyle_messageSummary];
                
                [[EaseMob sharedInstance].chatManager setIsAutoFetchBuddyList:YES];
                
                [HUD hideFromViewAnimated:YES];
            } else {
                switch (error.errorCode)
                {
                        
                        
                        
                    case EMErrorServerTooManyOperations:
                        break;
                        //                    case EMErrorNotFound:
                        //                        //不存在
                        //                        break;
                    case EMErrorNetworkNotConnected:
                        //EMErrorNetworkNotConnected
                        break;
                    case EMErrorServerNotReachable:
                        //连接服务器问题
                        break;
                        //                    case EMErrorServerAuthenticationFailure:
                        //                      //获取token失败
                        //                        break;
                        //                    case EMErrorServerTimeout:
                        //                       //连接超时
                        //                        break;
                    default:
                    {
                        [self loginFeated:user];
                    }
                        
                        break;
                }[
                  HUD hideFromViewAnimated:YES];
                
            }
        } onQueue:nil];
    }
}
// 登录环信账号,主动登录调用方法,需要重新加载好友关系,喜欢的人,喜欢的文章
//
- (void)loginToEasemob{
     
    [self autologinToEasemob];
    
    MLUser *user = [MLUser currentUser];
    if (user&&[MLUser currentUser].isUserInited&&MLUserStatus_DISABLE != user.status) {
        [self loadFrinedAndLikeData];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"sweetheartChange" object:self userInfo:nil];
    }
}
- (void)loadFrinedAndLikeData
{
    //加载好友关系
    //加载喜欢的人
    [self loadFriendsData];
    [self loadLikeUserData];
    [self loadLikeArticleData];
}
//再次加载喜欢的人
- (void)againLoadLikeUserDataSkip:(NSInteger)skip mDic:(NSMutableDictionary *)mdic
{
    
    AVQuery *likeUserQuery = [MLUserLike query];
    [likeUserQuery includeKey:@"likeUser"];
    [likeUserQuery whereKey:@"user" equalTo:[MLUser currentUser]];
    likeUserQuery.limit = kNumber;
    likeUserQuery.skip = skip;
    likeUserQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    likeUserQuery.maxCacheAge = 7200;
    [likeUserQuery orderByDescending:@"createdAt"];
    [likeUserQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
           
            for (MLUserLike *userLike in objects) {
                [mdic setObject:@"YES" forKey:userLike.likeUser.objectId];
            }
            if (objects && objects.count == kNumber) {
                [self againLoadLikeUserDataSkip:skip+kNumber mDic:mdic];
            }
            [Utils savePassLoveuUserDictionary:mdic];
            //请求完数据,发送通知告诉空闲恋人页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"OnlineTableViewReloadData" object:self userInfo:nil];
        }
    }];
    
}
//加载喜欢的人
- (void)loadLikeUserData
{
    
    AVQuery *likeUserQuery = [MLUserLike query];
    [likeUserQuery includeKey:@"likeUser"];
    [likeUserQuery whereKey:@"user" equalTo:[MLUser currentUser]];
    likeUserQuery.limit = kNumber;
    likeUserQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    likeUserQuery.maxCacheAge = 7200;
    [likeUserQuery orderByDescending:@"createdAt"];
    [likeUserQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            NSMutableDictionary *d = [NSMutableDictionary dictionary];
            for (MLUserLike *userLike in objects) {
                [d setObject:@"YES" forKey:userLike.likeUser.objectId];
            }
            if (objects && objects.count == kNumber) {
                [self againLoadLikeUserDataSkip:kNumber mDic:d];
            }
            [Utils savePassLoveuUserDictionary:d];
            //请求完数据,发送通知告诉空闲恋人页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"OnlineTableViewReloadData" object:self userInfo:nil];
        }
    }];
    
}
- (void)againLoadLikeArticleDataSkip:(NSInteger)skip mDic:(NSMutableDictionary *)mdic
{
    // 获取喜欢过的文章记录
    AVQuery *articleLikeQuery = [MLArticleLike query];
    [articleLikeQuery includeKey:@"article"];
    [articleLikeQuery whereKey:@"user" equalTo:[MLUser currentUser]];
    articleLikeQuery.limit = kNumber;
    articleLikeQuery.skip = skip;
    articleLikeQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    articleLikeQuery.maxCacheAge = 7200;
    [articleLikeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
           
            for (MLArticleLike *userLike in objects) {
                [mdic setObject:@"YES" forKey:userLike.article.objectId];
            }
            if (objects && objects.count == kNumber) {
                [self againLoadLikeArticleDataSkip:skip+kNumber mDic:mdic];
            }
            [Utils savePassLoveuArticleDictionary:mdic];
            //请求完数据,发送通知告诉空闲恋人页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RecommendTableViewReloadData" object:self userInfo:nil];
        }
    }];

}
//加载喜欢的文章
- (void)loadLikeArticleData
{
    // 获取喜欢过的文章记录
    AVQuery *articleLikeQuery = [MLArticleLike query];
    [articleLikeQuery includeKey:@"article"];
    [articleLikeQuery whereKey:@"user" equalTo:[MLUser currentUser]];
    articleLikeQuery.limit = kNumber;
    articleLikeQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    articleLikeQuery.maxCacheAge = 7200;
    [articleLikeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            NSMutableDictionary *d = [NSMutableDictionary dictionary];
            for (MLArticleLike *userLike in objects) {
                [d setObject:@"YES" forKey:userLike.article.objectId];
            }
            if (objects && objects.count == kNumber) {
                [self againLoadLikeArticleDataSkip:kNumber mDic:d];
            }
            [Utils savePassLoveuArticleDictionary:d];
            //请求完数据,发送通知告诉空闲恋人页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RecommendTableViewReloadData" object:self userInfo:nil];
        }
    }];
}
// 加载好友关系(不是好友的时候,是否需要再次查询是否为好友,是否需要加为好友)
- (void)loadFriendsData {
    // 使用followee表里面用户关注的对象初始化friendsArray
    MLUser *currentUser = [MLUser currentUser];
    AVQuery *followeeQuery = [MLUser followeeQuery:currentUser.objectId];
    [followeeQuery includeKey:@"followee"];
    followeeQuery.limit = kNumber;
    [followeeQuery orderByDescending:@"createdAt"];
    [followeeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 初始化好友列表
            [ShareData shareData].friends = [NSMutableArray arrayWithArray:objects];
            NSMutableDictionary *d = [NSMutableDictionary dictionary];
            for (MLUser *u in objects) {
                [d setObject:@"YES" forKey:u.objectId];
            }
            if(objects &&objects.count == kNumber){
                // NSInteger skip = kNumber;
                [self againloadFriendsDataSkip:kNumber mDic:d];
            }
            
            [Utils savePassFriendDictionary:d];
            //请求完数据,发送通知告诉好友页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMyFriendsData" object:self userInfo:nil];
        }
    }];
}
- (void)againloadFriendsDataSkip:(NSInteger )skip mDic:(NSMutableDictionary *)mdic
{
    MLUser *currentUser = [MLUser currentUser];
    AVQuery *followeeQuery = [MLUser followeeQuery:currentUser.objectId];
    [followeeQuery includeKey:@"followee"];
    followeeQuery.limit = kNumber;
    followeeQuery.skip = skip;
    [followeeQuery orderByDescending:@"createdAt"];
    [followeeQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (!error) {
            // 初始化好友列表
            [[ShareData shareData].friends addObjectsFromArray:objects];
            for (MLUser *u in objects) {
                [mdic setObject:@"YES" forKey:u.objectId];
            }
            if(objects &&objects.count == kNumber){
                [self againloadFriendsDataSkip:skip+kNumber mDic:mdic];
            }
           
            [Utils savePassFriendDictionary:mdic];
            //请求完数据,发送通知告诉恋人页面刷新数据
            [[NSNotificationCenter defaultCenter] postNotificationName:@"loadMyFriendsData" object:self userInfo:nil];
        }
    }];
}

- (void)loginFeated:(MLUser *)user
{
    NSDictionary *params = @{@"username": user.objectId,@"nickname":user.nickname,@"password":[self md5:user.objectId]};
    [AVCloud callFunctionInBackground:@"register" withParameters:params block:^(id object, NSError *errorr) {
        if (!errorr) {
            [HUD setOnViewWithTitle:@"登录中" animated:YES];
            NSLog(@"注册成功");
            [user refreshInBackgroundWithBlock:nil];
            // 重新登录
            [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:user.objectId password:[self md5:user.objectId] completion:^(NSDictionary *loginInfo, EMError *error) {
                 [HUD hideFromViewAnimated:YES];
                if (!error && loginInfo) {
                   
                    //获取群组列表
                    [[EaseMob sharedInstance].chatManager asyncFetchMyGroupsList];
                    [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
                    [[EaseMob sharedInstance].chatManager setApnsNickname:user.nickname];
                    
                    [[EaseMob sharedInstance].chatManager.pushNotificationOptions setDisplayStyle:ePushNotificationDisplayStyle_messageSummary];
                    NSLog(@"登录成功");
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"logOutSucceed" object:nil];
        
                    [self inituserdata];
                    [self autoLogin];
                    [HUD hideFromViewAnimated:YES];
                    
                }else{
                    [HUD Prompt:@"登陆出错"];
                    [self appOut];
                    [HUD hideFromViewAnimated:YES];
                    return ;
                }
            } onQueue:nil];
        }else{
            
            
        }
    }];
}
-(void)appOut
{
     [[NSNotificationCenter defaultCenter] postNotificationName:@"OnlineTableViewReloadData" object:self userInfo:nil];
     [[NSNotificationCenter defaultCenter] postNotificationName:@"RecommendTableViewReloadData" object:self userInfo:nil];
    // 退订推送
    MLUser *user = [MLUser currentUser];
    if (user) {
        //退出登录
        [Utils quitLogin];
        [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
           
            if(error){
                [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
                   
                } onQueue:nil];
            }
        } onQueue:nil];
    }
}

-(void)autoLogin
{
    [[EaseMob sharedInstance].chatManager asyncLoginWithUsername:[MLUser currentUser].objectId password:[self md5:[MLUser currentUser].objectId] completion:^(NSDictionary *loginInfo, EMError *error) {
        [HUD hideFromViewAnimated:YES];
        if (!error && loginInfo) {
            NSLog(@"登录成功");
            [[EaseMob sharedInstance].chatManager setApnsNickname:[MLUser currentUser].nickname];
            // 设置自动登录
            [self inituserdata];
            [[EaseMob sharedInstance].chatManager.pushNotificationOptions setDisplayStyle:ePushNotificationDisplayStyle_messageSummary];
            [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:YES];
            
        } else {
            if (biaoji <5) {
                [self autoLogin];
                biaoji ++;
            }
        }
    } onQueue:nil];
}



///发送系统消息
-(void)inituserdata
{
    [self installation];
    EMPushNotificationOptions *p = [[EMPushNotificationOptions alloc] init];
    p.nickname = [MLUser currentUser].nickname;
    p.displayStyle = ePushNotificationDisplayStyle_messageSummary;
    [[EaseMob sharedInstance].chatManager asyncUpdatePushOptions:p completion:^(EMPushNotificationOptions *options, EMError *error) {
        if(!error){
            // [HUD Prompt:@"设置成功"];
            NSUserDefaults *u =[NSUserDefaults standardUserDefaults];
            NSDictionary *dic = [u objectForKey: [NSString stringWithFormat:@"%@myswitchdic",[MLUser currentUser].objectId]];
            NSMutableDictionary *switchDic = [NSMutableDictionary dictionaryWithDictionary:dic];
            [switchDic setObject:@"YES" forKey:@"notification"];
            [u setObject:switchDic forKey: [NSString stringWithFormat:@"%@myswitchdic",[MLUser currentUser].objectId]];
            [u synchronize];
        }else{
            
        }
    } onQueue:nil];
    
    if ([Utils onePerform:@"sendSysLoginMsg"]) {
        NSDictionary *params = @{@"touserId":[MLUser currentUser].objectId,@"type":[NSNumber numberWithInteger:1]};
        [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:params block:^(id object, NSError *error) {
            if (error) {
            }
        }];
    }
}


- (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}


- (void)applicationWillResignActive:(UIApplication *)application {
    
    //    if ([ShareData shareData].shareTask) {
    //    }
    
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    //已经进入后台
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"applicationDidEnterBackground"];
    
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    //    if ([ShareData shareData].shareTask) {
    //        //
    //         [[NSNotificationCenter defaultCenter] postNotificationName:@"shareTask" object:self userInfo:nil];
    //        [ShareData shareData].shareTask = NO;
    //    }
    
    ////从后台进入前台
    [[ShareData shareData].homeVC.find findRefreshUsers];
    
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [[EaseMob sharedInstance] applicationWillEnterForeground:application];
    
    //已经进入前台
    BOOL isAutoLogin = [[EaseMob sharedInstance].chatManager isAutoLoginEnabled];
    //判断环信是否登录
    if (!isAutoLogin || ![[EaseMob sharedInstance].chatManager isConnected]) {
        [self onAutologinToEasemob];
    }
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
   
    //应用重新启动
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    //应用程序终止
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[EaseMob sharedInstance] applicationWillTerminate:application];
    AVInstallation *currentInstallation = [AVInstallation currentInstallation];
    [currentInstallation setBadge:0];
    [currentInstallation saveEventually];
    //[application cancelAllLocalNotifications];
}

#pragma mark - RCIMMessageReceiveDelegate

/*
 -(void)responseConnectionStatus:(RCConnectionStatus)status{
 if (ConnectionStatus_KICKED_OFFLINE_BY_OTHER_CLIENT == status) {
 
 // 退订推送
 MLUser *user = [MLUser currentUser];
 AVInstallation *installation = [AVInstallation currentInstallation];
 [installation removeObject:user.objectId forKey:@"channels"];
 [installation saveInBackground];
 // 断开融云连接
 [[RCIM sharedRCIM]disconnect:NO];
 // 退出登录
 [MLUser logOut];
 
 dispatch_async(dispatch_get_main_queue(), ^{
 // 发送退出登录的通知
 [[NSNotificationCenter defaultCenter]postNotificationName:NOTIFICATION_TYPE_LOGOUT_SUCCEED object:nil];
 
 // 退出登录, 并且现实提示
 [[TWMessageBarManager sharedInstance] showMessageWithTitle:@""
 description:@"该账号已在其他手机登录,自动退出"
 type:TWMessageBarMessageTypeInfo
 duration:60];
 });
 }
 }
 */

#pragma mark - easemob delegate


/*
 #pragma mark - weibo login
 
 - (void)didReceiveWeiboRequest:(WBBaseRequest *)request
 {
 
 }
 
 
 - (void)didReceiveWeiboResponse:(WBBaseResponse *)response
 {
 if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
 {
 NSString *title = NSLocalizedString(@"发送结果", nil);
 NSString *message = [NSString stringWithFormat:@"%@: %d\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode, NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil),response.requestUserInfo];
 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
 message:message
 delegate:nil
 cancelButtonTitle:NSLocalizedString(@"确定", nil)
 otherButtonTitles:nil];
 WBSendMessageToWeiboResponse* sendMessageToWeiboResponse = (WBSendMessageToWeiboResponse*)response;
 NSString* accessToken = [sendMessageToWeiboResponse.authResponse accessToken];
 if (accessToken)
 {
 self.wbtoken = accessToken;
 }
 NSString* userID = [sendMessageToWeiboResponse.authResponse userID];
 if (userID) {
 self.wbCurrentUserID = userID;
 }
 [alert show];
 }
 else if ([response isKindOfClass:WBAuthorizeResponse.class])
 {
 NSString *title = NSLocalizedString(@"认证结果", nil);
 NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.userId: %@\nresponse.accessToken: %@\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode,[(WBAuthorizeResponse *)response userID], [(WBAuthorizeResponse *)response accessToken],  NSLocalizedString(@"响应UserInfo数据", nil), response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];
 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
 message:message
 delegate:nil
 cancelButtonTitle:NSLocalizedString(@"确定", nil)
 otherButtonTitles:nil];
 
 self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
 self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
 
 [Utils saveToDefaults:self.wbtoken forKey:@"WBAccessToken"];
 [Utils saveToDefaults:self.wbCurrentUserID forKey:@"WBCurrentUserID"];
 
 
 
 NSLog(@"授权成功的WBAccessToken:%@",[Utils defaultsForKey:@"WBAccessToken"]);
 NSLog(@"授权成功的WBCurrentUserID:%@",[Utils defaultsForKey:@"WBCurrentUserID"]);
 
 
 [[NSNotificationCenter defaultCenter] postNotificationName:@"authorizationSucceed" object:self userInfo:nil];
 NSLog(@"%@",message);
 
 [alert show];
 }
 else if ([response isKindOfClass:WBPaymentResponse.class])
 {
 NSString *title = NSLocalizedString(@"支付结果", nil);
 NSString *message = [NSString stringWithFormat:@"%@: %d\nresponse.payStatusCode: %@\nresponse.payStatusMessage: %@\n%@: %@\n%@: %@", NSLocalizedString(@"响应状态", nil), (int)response.statusCode,[(WBPaymentResponse *)response payStatusCode], [(WBPaymentResponse *)response payStatusMessage], NSLocalizedString(@"响应UserInfo数据", nil),response.userInfo, NSLocalizedString(@"原请求UserInfo数据", nil), response.requestUserInfo];
 UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
 message:message
 delegate:nil
 cancelButtonTitle:NSLocalizedString(@"确定", nil)
 otherButtonTitles:nil];
 [alert show];
 }
 }
 */

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
//{
//    return [WeiboSDK handleOpenURL:url delegate:self];
//}

-(void) onResp:(BaseResp*)resp
{
    /*     ErrCode ERR_OK = 0(用户同意)
     ERR_AUTH_DENIED = -4（用户拒绝授权）
     ERR_USER_CANCEL = -2（用户取消）
     code    用户换取access_token的code，仅在ErrCode为0时有效
     state   第三方程序发送时用来标识其请求的唯一性的标志，由第三方程序调用sendReq时传入，由微信终端回传，state字符串长度不能超过1K
     lang    微信客户端当前语言
     country 微信用户当前国家信息
     */
    SendAuthResp *aresp = (SendAuthResp *)resp;
    if (aresp.errCode== 0) {
        NSString *code;
        @try {
            // 可能会出现崩溃的代码
            code = aresp.code;
            self.wxCode = code;
            [self getAccess_token];
        }
        @catch (NSException *exception) {
            // 捕获到的异常exception
        }
    }
    
}

-(void)getAccess_token  {
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",@"wxaa055b4833fdbf4a",@"c4f199bd5983ae9309c8bcb4f3bcd0e4",self.wxCode];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                self.wxAccessToken = [dic objectForKey:@"access_token"];
                self.wxOpenid = [dic objectForKey:@"openid"];
                [self getUserInfo];
            }
        });
    });
}

-(void)getUserInfo  {
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",self.wxAccessToken,self.wxOpenid];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (data) {
                //*  @param  authData     SNS平台登录返回的用户验证数据. 必需包含字段:`id`,`access_token`,`expires_at`,`platform`
                NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                //确定账号的过期时间= 账号创建的时间 + 有效期
                NSTimeInterval secondsPerDay = (24*7) * 60 * 60;
                NSDate *tomorrow = [[NSDate alloc] initWithTimeIntervalSinceNow:secondsPerDay];
                [dic setObject:self.wxOpenid forKey:@"id"];
                [dic setObject:self.wxAccessToken forKey:@"access_token"];
                [dic setObject:tomorrow forKey:@"expires_at"];
                [dic setObject:[NSNumber numberWithInteger:2] forKey:@"platform"];
                [dic setObject:[dic objectForKey:@"headimgurl"] forKey:@"avatar"];
                [dic setObject:[dic objectForKey:@"nickname"] forKey:@"username"];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"WXLogin" object:self userInfo:dic];
                
            }
        });
    });
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    
    return [UMSocialSnsService handleOpenURL:url]|| [WXApi handleOpenURL:url delegate:self] || [AVOSCloudSNS handleOpenURL:url];
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    return  [UMSocialSnsService handleOpenURL:url]||[WXApi handleOpenURL:url delegate:self] || [AVOSCloudSNS handleOpenURL:url];
}



@end